﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronCow;
using Milkify.Interfaces;
using Milkify.Data;
using Milkify.Input;

namespace Milkify.Controllers
{
    public class TaskNoteEditController : Controller
    {
        private ITaskNoteEditView mView;

        public TaskNoteEditController(ControllerContext context, Rtm rtm, IViewContainer viewContainer, IViewFactory viewFactory)
            : base(context, rtm, viewContainer)
        {
            mView = (ITaskNoteEditView)viewFactory.Create("TaskNoteEdit");
            mView.EditComplete += new EventHandler(View_EditComplete);
            mView.EditCancelled += new EventHandler(View_EditCancelled);
        }

        public override void Execute()
        {
            if (Context.CommandName == "EditTaskNote")
            {
                var parameter = Context.CommandParameter as NavigateToTaskNoteParameter;
                if (parameter == null)
                    throw new InvalidOperationException("No task note parameter was given.");

                var viewData = new TaskNoteViewData(parameter.TaskNote);
                mView.ViewData = viewData;

                ViewContainer.NavigateToView(mView);
            }
            else if (Context.CommandName == "AddTaskNote")
            {
                TaskNote note = new TaskNote();
                mView.ViewData = new TaskNoteViewData(note);

                ViewContainer.NavigateToView(mView);
            }
            else
            {
                throw new InvalidOperationException(string.Format("The command name '{0}' is not valid.", Context.CommandName));
            }
        }

        private void View_EditCancelled(object sender, EventArgs e)
        {
        }

        private void View_EditComplete(object sender, EventArgs e)
        {
            if (Context.CommandName == "AddTaskNote")
            {
                Task task = Context.CommandParameter as Task;
                if (task == null)
                    throw new InvalidOperationException("No task was given for which to set this newly created note.");
                var viewData = (TaskNoteViewData)mView.ViewData;
                task.Notes.Add(viewData.TaskNote);
            }
        }
    }
}
